package com.shenmazong.serveruserapi.controller;

//import com.google.inject.internal.asm.$AnnotationVisitor;
import com.shenmazong.serveruserapi.util.JwtTokenUtils;
import com.shenmazong.utils.ConstUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.ws.RequestWrapper;

@Controller
public class TokenController {

    @RequestMapping(value = "/login")
    public String doLogin() {
        return "login";
    }


    @RequestMapping(value = "/getToken")
    @ResponseBody
    public String getToken() {
        return JwtTokenUtils.makeToken(999, "张飞");
    }

    @RequestMapping(value = "/checkToken")
    @ResponseBody
    public String checkToken(@RequestParam("userId") Integer userId,
                             @RequestParam("token") String token) {
        Integer uid = 0;
        String nickName = null;
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(ConstUtils.TOKEN_PASS_WORD)
                    .parseClaimsJws(token)
                    .getBody();

            uid = Integer.valueOf(claims.getId());
            nickName = claims.getSubject();
        }
        catch (ExpiredJwtException e) {
//            claims = e.getClaims();
//            uid = Integer.valueOf(claims.getId());
//            nickName = claims.getSubject();
            System.out.println("token expired");
        } catch (SignatureException e) {
            System.out.println("token signature error");
        } catch (Exception e) {
            System.out.println("token error");
        }

        //
        if(uid != 0) {
            return "ok";
        }
        else {
            return "error";
        }
    }
}
